package com.logger.handlers;

import com.logger.LogMessage;
import com.logger.common.FilePicker;
import com.logger.common.StorageUtils;
import com.logger.common.Utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 输出到文件中
 * Created by chenxunlin01 on 2016/1/17.
 */

public class FileHandler extends AHandler {

    //读取流的缓存
    private static final int DEFAULT_BUF_SIZE = 8192;
    //文件工具类
    protected FilePicker filePicker = new FilePicker();

    /**
     * 文件名称
     */
    protected String fileName;
    protected int bufferSize = DEFAULT_BUF_SIZE;
    /**
     * 是否往文件中继续添加内容
     */
    protected boolean fileAppend = true;
    protected OutputStream outStream;

    @Override
    public void handler(LogMessage msg, String log) throws Exception {
        createFile(fileName, fileAppend, bufferSize);

        if (outStream == null) {
            return;
        }

        byte[] data = log.getBytes("UTF-8");
        outStream.write(data);
        outStream.flush();
        Utils.closeIO(outStream);
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = StorageUtils.getSdcardPath() + File.separator + fileName;
    }

    private String createFile(String path, boolean append, int bufSize) throws IOException {
        OutputStream fos = filePicker.getOutputStream(path, append);
        if (fos != null) {
            outStream = new BufferedOutputStream(fos, bufferSize);
        }
        return path;
    }
}
